<template>
  <div class="supplier-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>供应商管理</span>
          <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增供应商</el-button>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="供应商编码">
          <el-input
            v-model="searchForm.supplier_code"
            placeholder="请输入供应商编码"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchForm.supplier_name"
            placeholder="请输入供应商名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="供应商类型">
          <el-select
            v-model="searchForm.supplier_type"
            placeholder="请选择供应商类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(label, value) in supplierTypeOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <!-- 移除：信用等级搜索条件（SupplierQueryParams中不存在该属性） -->
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.is_active"
            placeholder="请选择状态"
            clearable
            style="width: 180px"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 供应商列表 -->
      <el-table
        v-loading="supplierStore.loading"
        :data="supplierStore.paginatedSuppliers"
        style="width: 100%"
        border
      >
        <el-table-column prop="supplier_code" label="供应商编码" width="120" />
        <el-table-column prop="supplier_name" label="供应商名称" width="180" />
        <el-table-column prop="supplier_type" label="供应商类型" width="120">
          <template #default="scope">
            {{ getSupplierTypeLabel(scope.row.supplier_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="contact_person" label="联系人" width="120" />
        <el-table-column prop="contact_phone" label="联系电话" width="150" />
        <el-table-column prop="email" label="电子邮箱" width="180" />
        <el-table-column prop="tax_number" label="税号" width="180" />
        <el-table-column prop="credit_rating" label="信用等级" width="120">
          <template #default="scope">
            {{ getCreditRatingLabel(scope.row.credit_rating) }}
          </template>
        </el-table-column>
        <el-table-column prop="payment_terms" label="付款条件" width="150" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_active"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link danger @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="supplierStore.currentPage"
          v-model:page-size="supplierStore.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="supplierStore.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑供应商对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="supplierFormRef"
        :model="supplierForm"
        :rules="formRules"
        label-width="140px"
        class="dialog-form"
      >
        <el-form-item label="供应商编码" prop="supplier_code">
          <el-input
            v-model="supplierForm.supplier_code"
            placeholder="请输入供应商编码"
            clearable
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplier_name">
          <el-input
            v-model="supplierForm.supplier_name"
            placeholder="请输入供应商名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="供应商类型" prop="supplier_type">
          <el-select
            v-model="supplierForm.supplier_type"
            placeholder="请选择供应商类型"
            clearable
          >
            <el-option
              v-for="(label, value) in supplierTypeOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contact_person">
          <el-input
            v-model="supplierForm.contact_person"
            placeholder="请输入联系人姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input
            v-model="supplierForm.contact_phone"
            placeholder="请输入联系电话"
            clearable
          />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="supplierForm.email"
            placeholder="请输入电子邮箱"
            type="email"
            clearable
          />
        </el-form-item>
        <el-form-item label="供应商地址" prop="address">
          <el-input
            v-model="supplierForm.address"
            placeholder="请输入供应商地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="税号" prop="tax_number">
          <el-input
            v-model="supplierForm.tax_number"
            placeholder="请输入税号"
            clearable
          />
        </el-form-item>
        <el-form-item label="开户银行" prop="bank_name">
          <el-input
            v-model="supplierForm.bank_name"
            placeholder="请输入开户银行"
            clearable
          />
        </el-form-item>
        <el-form-item label="银行账号" prop="bank_account">
          <el-input
            v-model="supplierForm.bank_account"
            placeholder="请输入银行账号"
            clearable
          />
        </el-form-item>
        <el-form-item label="付款条件" prop="payment_terms">
          <el-input
            v-model="supplierForm.payment_terms"
            placeholder="请输入付款条件"
            clearable
          />
        </el-form-item>
        <el-form-item label="信用等级" prop="credit_rating">
          <el-select
            v-model="supplierForm.credit_rating"
            placeholder="请选择信用等级"
            clearable
          >
            <el-option
              v-for="(label, value) in creditRatingOptions"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useBaseSupplierStore } from '@/stores/base/BaseSupplierStore';
import type { Supplier, SupplierQueryParams, SupplierCreateParams, SupplierUpdateParams } from '@/types/base/BaseSupplier';

// 供应商类型选项
const supplierTypeOptions: Record<number, string> = {
  1: '原材料供应商',
  2: '零部件供应商',
  3: '成品供应商',
  4: '服务供应商'
};

// 信用等级选项
const creditRatingOptions: Record<number, string> = {
  1: 'AAA',
  2: 'AA',
  3: 'A',
  4: 'BBB',
  5: 'BB'
};

// 获取供应商类型标签
const getSupplierTypeLabel = (type: number): string => {
  return supplierTypeOptions[type] || '未知类型';
};

// 获取信用等级标签
const getCreditRatingLabel = (rating: number): string => {
  return creditRatingOptions[rating] || '未评级';
};

// 表单验证规则
const formRules = reactive({
  supplier_code: [
    { required: true, message: '请输入供应商编码', trigger: 'blur' },
    { min: 2, max: 50, message: '供应商编码长度应在 2-50 个字符之间', trigger: 'blur' }
  ],
  supplier_name: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 100, message: '供应商名称长度应在 2-100 个字符之间', trigger: 'blur' }
  ],
  supplier_type: [
    { required: true, message: '请选择供应商类型', trigger: 'change' }
  ],
  contact_person: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contact_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  credit_rating: [
    { required: true, message: '请选择信用等级', trigger: 'change' }
  ]
});

// 搜索表单
const searchForm = reactive<SupplierQueryParams>({
  supplier_code: undefined,
  supplier_name: undefined,
  supplier_type: undefined,
  // 移除：credit_rating属性（SupplierQueryParams中不存在）
  is_active: undefined
});

// 对话框状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = computed(() => isEdit.value ? '编辑供应商' : '新增供应商');

// 表单数据
const supplierForm = reactive({
  supplier_id: 0,
  supplier_code: '',
  supplier_name: '',
  supplier_type: undefined,
  contact_person: '',
  contact_phone: '',
  email: '',
  address: '',
  tax_number: '',
  bank_name: '',
  bank_account: '',
  payment_terms: '',
  credit_rating: undefined
});

// 表单引用
const supplierFormRef = ref();

// Store实例
const supplierStore = useBaseSupplierStore();

// 初始化加载数据
onMounted(() => {
  loadSuppliers();
});

// 加载供应商列表
const loadSuppliers = async () => {
  try {
    await supplierStore.getSuppliers({
      ...searchForm,
      page_number: supplierStore.currentPage,
      page_size: supplierStore.pageSize
    });
  } catch (error) {
    ElMessage.error('加载供应商列表失败');
  }
};

// 处理搜索
const handleSearch = () => {
  supplierStore.setQueryParams(searchForm);
  loadSuppliers();
};

// 处理重置
const handleReset = () => {
  // 显式重置每个字段，避免使用索引导致的any类型问题
  searchForm.supplier_code = undefined;
  searchForm.supplier_name = undefined;
  searchForm.supplier_type = undefined;
  searchForm.is_active = undefined;
  supplierStore.resetQueryParams();
  loadSuppliers();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  supplierStore.setPagination(1, size);
  loadSuppliers();
};

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  supplierStore.setPagination(current, supplierStore.pageSize);
  loadSuppliers();
};

// 处理新增
const handleAdd = () => {
  isEdit.value = false;
  // 显式重置表单字段（修复索引类型错误）
  supplierForm.supplier_id = 0;
  supplierForm.supplier_code = '';
  supplierForm.supplier_name = '';
  supplierForm.supplier_type = undefined;
  supplierForm.contact_person = '';
  supplierForm.contact_phone = '';
  supplierForm.email = '';
  supplierForm.address = '';
  supplierForm.tax_number = '';
  supplierForm.bank_name = '';
  supplierForm.bank_account = '';
  supplierForm.payment_terms = '';
  supplierForm.credit_rating = undefined;
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row: Supplier) => {
  try {
    // 修复：getSupplierDetail直接返回Supplier类型，无需访问.data
    const detail = await supplierStore.getSupplierDetail(row.supplier_id);

    if (detail) {
      isEdit.value = true;
      // 复制数据到表单
      Object.assign(supplierForm, {
        supplier_id: detail.supplier_id,
        supplier_code: detail.supplier_code,
        supplier_name: detail.supplier_name,
        supplier_type: detail.supplier_type,
        contact_person: detail.contact_person,
        contact_phone: detail.contact_phone,
        email: detail.email,
        address: detail.address,
        tax_number: detail.tax_number,
        bank_name: detail.bank_name,
        bank_account: detail.bank_account,
        payment_terms: detail.payment_terms,
        credit_rating: detail.credit_rating
      });
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('获取供应商详情失败');
  }
};

// 处理提交
const handleSubmit = async () => {
  if (!supplierFormRef.value) return;

  try {
    // 表单验证（确保必填字段有值）
    await supplierFormRef.value.validate();

    // 使用非空断言（!）替代强制类型转换（修复类型转换错误）
    const submitData = {
      ...supplierForm,
      supplier_type: supplierForm.supplier_type!,  // 表单验证确保有值
      credit_rating: supplierForm.credit_rating!   // 表单验证确保有值
    };

    if (isEdit.value) {
      const params: SupplierUpdateParams = submitData;
      await supplierStore.updateSupplier(params);
      ElMessage.success('供应商更新成功');
    } else {
      const params: SupplierCreateParams = submitData;
      await supplierStore.createSupplier(params);
      ElMessage.success('供应商创建成功');
    }

    dialogVisible.value = false;
    loadSuppliers();
  } catch (error) {
    // 表单验证失败或API调用失败不处理，已有相应提示
  }
};

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false;
  supplierFormRef.value?.resetFields();
};

// 处理状态变更
const handleStatusChange = async (row: Supplier) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.is_active ? '禁用' : '启用'}该供应商吗？`,
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await supplierStore.toggleSupplierStatus({
      supplier_id: row.supplier_id,
      is_active: row.is_active
    });
    loadSuppliers();
  } catch (error) {
    // 恢复状态
    row.is_active = !row.is_active;
    if (error !== 'cancel') {
      ElMessage.error('状态变更失败');
    }
  }
};

// 处理删除
const handleDelete = async (row: Supplier) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该供应商吗？此操作不可撤销！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    );

    await supplierStore.deleteSupplier(row.supplier_id);
    loadSuppliers();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};
</script>

<style scoped>
.supplier-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-form {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 10px;
}
</style>
